<template>
  <div class="main-content">
    <el-row class="main-row">
      <el-col class="main-left" :span="4">
        <el-tree
          class="tree-line"
          :data="leftTreeData"
          :props="props"
          :indent="0"
          :load="loadNode"
          lazy
          :expand-on-click-node="false"
          @current-change="treeChange"
        >
          <template #default="{ node, data }">
            <span v-if="data.groupName">
              <FolderOpened
                style="width: 20px; height: 20px; min-width: 20px; min-height: 20px; vertical-align: -4px"
              />
              <span>{{ data.groupName }}</span>
            </span>
            <span v-if="data.subTypeName">
              <Iphone style="width: 20px; height: 20px; min-width: 20px; min-height: 20px; vertical-align: -4px" />
              <span>{{ data.subTypeName + data.deviceSn }}</span>
            </span>
          </template>
        </el-tree>
      </el-col>
      <el-col class="main-right" :span="20">
        <el-form ref="deviceSearchRef" :model="deviceSearchData" :inline="true">
          <el-form-item class="item-width" label="起止时间" prop="deviceTime">
            <el-date-picker
              class="item-width-in"
              v-model="deviceSearchData.deviceTime"
              placeholder="请选择时间"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :clearable="false"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="['2000-01-01 00:00:00', '2000-01-01 23:59:59']"
              :shortcuts="shortcuts"
            />
          </el-form-item>
          <el-form-item class="item-width">
            <el-button type="primary" @click="search"> 查询 </el-button>
          </el-form-item>
          <el-form-item class="item-width">
            <el-button type="primary" @click="changeTheme"> 切换主题 {{theme}} </el-button>
          </el-form-item>
        </el-form>
        <el-row class="chart-content" v-show="hasData">
          <el-form class="filter" ref="filterRef" :model="filterData" :inline="true">
            <el-form-item class="item-width" prop="optionVal">
              <el-select
                style="width: 100px"
                v-model="filterData.optionVal"
                placeholder="请选择"
                @change="selectChange"
              >
                <el-option v-for="item in optionList" :key="item.label" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item class="item-width">
              <el-switch v-model="filterData.peakValue" active-text="峰值" @change="changePeak" />
            </el-form-item>
            <el-form-item class="item-width">
              <el-switch v-model="filterData.threshold" active-text="阈值" @change="changeThreshold" />
            </el-form-item>
            <el-form-item class="item-width">
              <el-switch v-model="filterData.realTime" active-text="实时数据" @change="changeRealTime" />
            </el-form-item>
            <el-form-item class="item-width">
              <el-checkbox-group v-model="filterData.checkVal" @change="checkboxChange">
                <el-checkbox v-for="item in checkboxList" :label="item.name" :key="item.label">
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          <el-slider
            class="slider"
            v-model="sliderValue"
            vertical
            height="180px"
            :step="1"
            :min="sliderMin"
            :max="sliderMax"
            :show-tooltip="true"
            @change="sliderChange"
          />
          <div id="lineChart"></div>
        </el-row>
        <el-row class="no-data" v-show="!hasData"> 暂无数据 </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts" name="manageData">
  import { onMounted, ref, Ref, watch, nextTick } from 'vue'
  import type Node from 'element-plus/es/components/tree/src/model/node'
  import { ECharts, graphic, EChartsOption } from 'echarts'
  import * as echarts from "echarts"
  import 'echarts/theme/gray'
  import 'echarts/theme/fruit'
  // import ha from '@/styles/ha.json'
  import dayjs from 'dayjs'
  import { initEcharts, useEcharts } from "@/hooks/useEcharts"

  onMounted(() => {
    _getDayNow()
    getLeft()
    initChart()
  })

  const baseData: any = {
    dataMap: [
      {
        unit: 'mm',
        name: 'x位移',
        label: 'xDistance'
      },
      {
        unit: 'mm',
        name: 'y位移',
        label: 'yDistance'
      },
      {
        unit: 'mm',
        name: 'z位移',
        label: 'zDistance'
      }
    ],
    dataList: [
      {
        timestamp: 1691633603000,
        xDistance: 20,
        yDistance: 21,
        zDistance: 88
      },
      {
        timestamp: 1691720003000,
        xDistance: 30,
        yDistance: 95,
        zDistance: 50
      },
      {
        timestamp: 1691806403000,
        xDistance: 80,
        yDistance: 41,
        zDistance: 70
      }
    ]
  }
  // 搜索框
  const deviceSearchRef = ref(null)
  const filterRef = ref(null)
  let deviceSearchData: any = ref({
    deviceTime: []
  })
  // 时间选择清空会变成null 转成[]
  watch(
      () => deviceSearchData.value.deviceTime,
      (newVal) => {
        if (newVal === null) {
          deviceSearchData.value.deviceTime = []
        }
      }
  )

  interface FilterData {
    optionVal: string
    peakValue: boolean
    threshold: boolean
    realTime: boolean
    checkVal: string[]
  }
  const filterData: Ref<FilterData> = ref({
    optionVal: '',
    peakValue: false,
    threshold: true,
    realTime: false,
    checkVal: []
  })

  const shortcuts = [
    {
      text: '最近一周',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
        return [start, end]
      }
    },
    {
      text: '最近1个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        return [start, end]
      }
    },
    {
      text: '最近3个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
        return [start, end]
      }
    }
  ]

  function search() {
    initChart()
  }

  // 单选
  interface OptionList {
    unit: string
    name: string
    label: string
  }
  const optionList: Ref<OptionList[]> = ref([])
  function selectChange(e: string) {
    checkboxList.value = initboxList.value.filter((i) => {
      return i.name !== e
    })
    filterData.value.checkVal = [e]
    // 筛选出当前值对应的数据
    let item = afterConverList.filter((i: any) => {
      return i.name === e
    })
    // 删除右侧Y轴
    if (eOption.yAxis.length > 1) {
      eOption.yAxis = eOption.yAxis.slice(0, 1)
    }
    _changeData(e, item[0])
  }

  // 多选
  interface CheckboxList {
    unit: string
    name: string
    label: string
  }
  const initboxList: Ref<CheckboxList[]> = ref([])
  const checkboxList: Ref<CheckboxList[]> = ref([])
  function checkboxChange(e: any) {
    _changeDataArr(e)
  }

  // 峰值
  function changePeak(e) {
    if (e) {
      eOption.series.forEach((i: any) => {
        i.markPoint.itemStyle.opacity = 1
      })
      useEcharts(echart, eOption)
    } else {
      eOption.series.forEach((i: any) => {
        i.markPoint.itemStyle.opacity = 0
      })
      useEcharts(echart, eOption)
    }
  }

  // 阈值
  function changeThreshold(e: any) {
    if (e) {
      eOption.series.forEach((i: any) => {
        i.markLine.data.forEach((j: any) => {
          j.lineStyle.opacity = 1
        })
      })
      useEcharts(echart, eOption)
    } else {
      eOption.series.forEach((i: any) => {
        i.markLine.data.forEach((j: any) => {
          j.lineStyle.opacity = 0
        })
      })
      useEcharts(echart, eOption)
    }
  }

  const realTimeData: any = {
    dataMap: [
      {
        unit: 'mm',
        name: 'x位移',
        label: 'xDistance'
      },
      {
        unit: 'mm',
        name: 'y位移',
        label: 'yDistance'
      },
      {
        unit: 'mm',
        name: 'z位移',
        label: 'zDistance'
      }
    ],
    dataList: [
      {
        timestamp: 1691933603000,
        xDistance: 30,
        yDistance: 50,
        zDistance: 60
      }
    ]
  }
  const realTimeData2: any = {
    dataMap: [
      {
        unit: 'mm',
        name: 'x位移',
        label: 'xDistance'
      },
      {
        unit: 'mm',
        name: 'y位移',
        label: 'yDistance'
      },
      {
        unit: 'mm',
        name: 'z位移',
        label: 'zDistance'
      }
    ],
    dataList: [
      {
        timestamp: 1692033603000,
        xDistance: 88,
        yDistance: 38,
        zDistance: 18
      }
    ]
  }
  const realTimeData3: any = {
    dataMap: [
      {
        unit: 'mm',
        name: 'x位移',
        label: 'xDistance'
      },
      {
        unit: 'mm',
        name: 'y位移',
        label: 'yDistance'
      },
      {
        unit: 'mm',
        name: 'z位移',
        label: 'zDistance'
      }
    ],
    dataList: [
      {
        timestamp: 1692133603000,
        xDistance: 18,
        yDistance: 38,
        zDistance: 48
      }
    ]
  }
  // 实施数据
  function changeRealTime(e) {
    if (e) {
      setTimeout(() => {
        afterConverList = _dataMapping(realTimeData)
        _changeRealTimeData(afterConverList)
      }, 1000)
      setTimeout(() => {
        afterConverList = _dataMapping(realTimeData2)
        _changeRealTimeData(afterConverList)
      }, 3000)
      setTimeout(() => {
        afterConverList = _dataMapping(realTimeData3)
        _changeRealTimeData(afterConverList)
      }, 4000)
    } else {
      // 删除右侧Y轴
      if (eOption.yAxis.length > 1) {
        eOption.yAxis = eOption.yAxis.slice(0, 1)
      }
      initChart()
    }
  }

  // 实时数据更新
  function _changeRealTimeData(arr) {
    let array = arr
    for (let key in array) {
      for (let key2 in eOption.series) {
        if (array[key].name === eOption.series[key2].name) {
          eOption.series[key2].data.push(...array[key].dataList)
        }
      }
    }
    // 设置markPoint
    _setMarkPoint()
    useEcharts(echart, eOption)
  }

  // silder范围
  const sliderValue = ref(0)
  const sliderMax = ref(100)
  const sliderMin = ref(0)
  function sliderChange(e) {
    let maxVal = afterConverList[0].max * 1.1 + e
    let minVal = afterConverList[0].min * 0.9 - e
    eOption.yAxis[0].max = maxVal
    eOption.yAxis[0].min = minVal
    eOption.yAxis[0].interval = (maxVal - minVal) / 5
    echart.setOption(eOption, true)
  }

  // 获取silder的值
  function _getSilder(max: number, min: number) {
    sliderMax.value = max
    sliderMin.value = 0
    sliderValue.value = 0
  }

  // echart
  let echartsDom: HTMLElement = undefined
  let echart: ECharts = undefined
  let eOption: EChartsOption = {
    title: {
      text: ""
    },
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        let html = ""
        params.map((item: any, index: number) => {
          if (index === 0) {
            html = `${item.seriesName}：${item.data[1]}${item.data[2]}<br />`
          } else {
            html += `${item.seriesName}：${item.data[1]}${item.data[2]}<br />`
          }
        })
        html += `时间：${params[0].data[0]}`
        if (params[0].seriesIndex === 0) {
          if (eOption.series[0].markLine.data.length > 0) {
            eOption.series.forEach((item, index) => {
              html += `<br /> ${item.name}：${item.markLine.data[0].name}${item.markLine.data[0].yAxis}${item.data[0][2]}`
              html += `<br /> ${item.name}：${item.markLine.data[1].name}${item.markLine.data[1].yAxis}${item.data[0][2]}`
            })
          }
        }
        return html
      }
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    legend: {
      data: []
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "100",
      containLabel: true
    },
    xAxis: {
      type: "time",
      boundaryGap: false,
      data: [],
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        formatter: (time: any) => {
          return dayjs(time).format("YYYY-MM-DD HH:mm:ss")
        }
      }
    },
    yAxis: [
      {
        type: "value",
        yAxisIndex: 0,
        name: "",
        axisLabel: {}
      }
    ],
    dataZoom: [
      {
        show: true,
        type: "slider",
        bottom: "70",
        height: 10, //组件高度
        fillerColor: new graphic.LinearGradient(1, 0, 0, 0, [
          {
            //给颜色设置渐变色 前面4个参数，给第一个设置1，第四个设置0 ，就是水平渐变
            //给第一个设置0，第四个设置1，就是垂直渐变
            offset: 0,
            color: "#1eb5e5"
          },
          {
            offset: 1,
            color: "#5ccbb1"
          }
        ]),
        backgroundColor: "#ddd", //两边未选中的滑动条区域的颜色
        showDataShadow: false, //是否显示数据阴影 默认auto
        showDetail: false,
        moveHandleSize: 0,
        handleIcon:
            "M-292,322.2c-3.2,0-6.4-0.6-9.3-1.9c-2.9-1.2-5.4-2.9-7.6-5.1s-3.9-4.8-5.1-7.6c-1.3-3-1.9-6.1-1.9-9.3c0-3.2,0.6-6.4,1.9-9.3c1.2-2.9,2.9-5.4,5.1-7.6s4.8-3.9,7.6-5.1c3-1.3,6.1-1.9,9.3-1.9c3.2,0,6.4,0.6,9.3,1.9c2.9,1.2,5.4,2.9,7.6,5.1s3.9,4.8,5.1,7.6c1.3,3,1.9,6.1,1.9,9.3c0,3.2-0.6,6.4-1.9,9.3c-1.2,2.9-2.9,5.4-5.1,7.6s-4.8,3.9-7.6,5.1C-285.6,321.5-288.8,322.2-292,322.2z"
      },
      {
        type: 'inside',
      }
    ],
    timeline: {
      bottom: "0",
      data: ["2023-08-10", "2023-08-11", "2023-08-12"]
    },
    series: [
      {
        name: "",
        data: [],
        type: "line",
        smooth: true,
        markLine: {
          data: [],
          symbol: "none"
        },
        markPoint: {
          data: []
        }
      }
    ],
  }
  let afterConverList: any = []
  let hasData = ref(false)

  async function getDeviceData() {
    for(let i = 0;i < 120000; i++) {
      const tmpItem = {
        timestamp: 1691633603000 + i * 1000,
        xDistance: 20 + i * 10,
        yDistance: 21 + i * 10,
        zDistance: 88 + i * 10
      }
      baseData.dataList.push(tmpItem)
    }
    console.log(baseData.dataList)
    if (baseData.dataList.length === 0) {
      hasData.value = false
    } else {
      hasData.value = true
      // 获取eOption
      optionList.value = baseData.dataMap
      filterData.value.optionVal = baseData.dataMap[0].name
      // 获取checkbox
      initboxList.value = JSON.parse(JSON.stringify(baseData.dataMap))
      checkboxList.value = initboxList.value.filter((i) => {
        return i.name !== filterData.value.optionVal
      })
      filterData.value.checkVal = [baseData.dataMap[0].name]
      // 设置series
      afterConverList = _dataMapping(baseData)
      console.log(afterConverList)
      _changeData(initboxList.value[0].name, afterConverList[0])
    }
  }

  function initChart() {
    echartsDom = document.getElementById('lineChart') as HTMLElement
    // echarts.registerTheme('ha', ha)
    // echart = echarts.init(echartsDom, theme.value) as ECharts
    //echart = initEcharts(echartsDom)
    echart = echarts.init(echartsDom, globalStore.getTheme)
    getDeviceData()
  }

  // 改变主题
  import { useGlobalStore } from '@/stores/modules/global'
  const globalStore = useGlobalStore()
  let theme = ref(globalStore.theme)
  const changeTheme = () => {
    if (theme.value === 'light') {
      globalStore.changeTheme('dark')
      theme.value = 'dark'
      echart.dispose()
      initChart()
    } else {
      globalStore.changeTheme('light')
      theme.value = 'light'
      echart.dispose()
      initChart()
    }
  }

  // 数据初始化，单选
  function _changeData(name: string, item: any) {
    nextTick(() => {
      echart.resize()
      // 设置series
      let valItem = item.dataList.map((i: any) => {
        return i
      })
      let serieItem = {
        name: name,
        data: valItem,
        type: 'line',
        yAxisIndex: 0,
        markLine: {
          symbol: 'none',
          data: []
        },
        smooth: true,
        showSymbol: false,
        hoverAnimation: false,
        areaStyle: {
          normal: {
            origin: "start",
            //线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
            color: new echarts.graphic.LinearGradient(
              0,
              0,
              0,
              1,
              [
                {
                  offset: 0,
                  color: "rgba(255,7,7,0.3)"
                },
                {
                  offset: 1,
                  color: "rgba(61,18,18,0.7)"
                }
              ],
              false
            ),
            shadowColor: "rgba(61,18,18,0.7)", //阴影颜色
            shadowBlur: 20 //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
          }
        },
      }
      let series: any = []
      series.push(serieItem)
      eOption.series = []
      eOption.series = series
      // 设置legend
      let legend: any = {
        data: [name]
      }
      eOption.legend = []
      eOption.legend = legend
      // 设置y轴
      let maxVal = item.max * 1.1
      let minVal = item.min * 0.9
      eOption.yAxis[0].max = maxVal
      eOption.yAxis[0].min = minVal
      eOption.yAxis[0].interval = (maxVal - minVal) / 5
      eOption.yAxis[0].name = item.name
      eOption.yAxis[0].axisLabel.formatter = function (val: any) {
        return `${val.toFixed(2)}${item.unit}`
      }
      // 设置markline
      _setMarkline([item.max, item.min])
      // 设置markPoint
      _setMarkPoint()
      // silder范围
      _getSilder(maxVal, minVal)
      console.log('eOption', eOption)
      useEcharts(echart, eOption, true)
    })
  }

  // 多选，多条数据适用
  function _changeDataArr(arr: string[]) {
    let array = arr
    // 设置series和legend
    let dataList: any = []
    // 顺序对应上
    for (let key in array) {
      for (let key2 in afterConverList) {
        if (array[key] === afterConverList[key2].name) {
          dataList.push(afterConverList[key2])
        }
      }
    }
    let series: any = []
    let legend: any = {
      data: []
    }
    dataList.forEach((i: any, idx: number) => {
      let reval = i.dataList.map((j: any) => {
        return j
      })
      // 设置markline
      const markLineData = {
        yAxis: i.max,
        symbol: 'none',
        lineStyle: {
          width: '1',
          color: '#ef2323',
          type: 'solid',
          opacity: 1
        },
        name: '上限',
        label: {
          formatter: ''
        }
      }
      const markLineData2 = {
        yAxis: i.min,
        symbol: 'none',
        lineStyle: {
          width: '1',
          color: '#ef2323',
          type: 'solid',
          opacity: 1
        },
        name: '下限',
        label: {
          formatter: ''
        }
      }
      let serieItem: any = {
        name: i.name,
        data: reval,
        type: 'line',
        smooth: true,
        markLine: {
          symbol: 'none',
          data: [markLineData, markLineData2]
        }
      }
      series.push(serieItem)
      legend.data.push(i.name)
    })
    eOption.series = series
    eOption.legend = legend
    // 设置y轴
    if (dataList.length > 1) {
      // y轴名字
      let nameArr = dataList.slice(1)
      let yName = ``
      nameArr.forEach((i: any, idx: number) => {
        if (idx === 0) {
          yName = `${i.name}`
        } else {
          yName += `,${i.name}`
        }
      })
      let maxVal = _getMaxMinArr(dataList).max * 1.1
      let minVal = _getMaxMinArr(dataList).min * 0.9
      let yaxisItem = {
        type: 'value',
        max: maxVal,
        min: minVal,
        yAxisIndex: 1,
        name: yName,
        interval: (maxVal - minVal) / 5,
        axisLabel: {
          formatter: function (val: any) {
            return `${val.toFixed(2)}${dataList[1].unit}`
          }
        }
      }
      _getSilder(maxVal, minVal)
      // 最多2个y轴
      eOption.yAxis = eOption.yAxis.slice(0, 1)
      eOption.yAxis.push(yaxisItem)
    } else {
      let maxVal = _getMaxMinArr(dataList).max * 1.1
      let minVal = _getMaxMinArr(dataList).min * 0.9
      eOption.yAxis[0].max = maxVal
      eOption.yAxis[0].min = minVal
      eOption.yAxis[0].interval = (maxVal - minVal) / 5
      _getSilder(maxVal, minVal)
      // 最多2个y轴
      eOption.yAxis = eOption.yAxis.slice(0, 1)
    }
    // 设置markPoint
    _setMarkPoint()
    useEcharts(echart, eOption, true)
  }

  // 设置markline
  function _setMarkline(arr: any[]) {
    const markLineData = {
      yAxis: _getMaxMinArr(arr).max,
      symbol: 'none',
      lineStyle: {
        width: '1',
        color: '#ef2323',
        type: 'solid',
        opacity: 1
      },
      name: '上限',
      label: {
        formatter: ''
      }
    }
    const markLineData2 = {
      yAxis: _getMaxMinArr(arr).min,
      symbol: 'none',
      lineStyle: {
        width: '1',
        color: '#ef2323',
        type: 'solid',
        opacity: 1
      },
      name: '下限',
      label: {
        formatter: ''
      }
    }
    for (let key in eOption.series) {
      eOption.series[key].markLine.data.push(markLineData)
      eOption.series[key].markLine.data.push(markLineData2)
    }
  }

  // 设置markPoint
  function _setMarkPoint() {
    eOption.series.forEach((i: any) => {
      i.markPoint = {
        label: {
          formatter: (params: any) => {
            return `${params.name}${params.value}${i.data[0][2]}`
          }
        },
        symbol: 'rect',
        symbolSize: [100, 30],
        symbolOffset: ['0', '-60%'],
        itemStyle: {
          color: '#e7ecec',
          opacity: 0
        },
        data: [
          { type: 'max', name: `${i.name}最大值` },
          { type: 'min', name: `${i.name}最小值` }
        ]
      }
    })
  }

  // 取最大最小值用于y轴
  function _getMaxMinArr(arr: any[]) {
    let combinedArr: any = []
    if (arr && arr[0].max) {
      for (let key in arr) {
        combinedArr.push(arr[key].max)
        combinedArr.push(arr[key].min)
      }
    } else {
      combinedArr = arr
    }
    let maxValue = Math.max(...combinedArr)
    let minValue = Math.min(...combinedArr)
    return {
      max: maxValue,
      min: minValue
    }
  }

  // 后端出来数据转换
  function _dataMapping(resdata: any) {
    const map = resdata.dataMap
    const data = resdata.dataList
    const list: any = []
    // 组合二维数组
    for (let key in map) {
      let a: any = {
        name: map[key].name,
        label: map[key].label,
        unit: map[key].unit,
        dataList: []
      }
      for (let key2 in data) {
        let b: any = []
        b[0] = dayjs(data[key2].timestamp).format("YYYY-MM-DD HH:mm:ss")
        b[1] = data[key2][map[key].label]
        b[2] = a.unit
        a.dataList.push(b)
      }
      list.push(a)
    }
    // 取最大最小值
    for (let key in list) {
      let dList: any = list[key].dataList
      let list2: any = []
      for (let key2 in dList) {
        list2.push(dList[key2][1])
      }
      list[key].max = Math.max(...list2)
      list[key].min = Math.min(...list2)
    }
    return list
  }

  // 向上取整10
  function _ceilToTen(num: number) {
    let ceilNum = Math.ceil((num + 5) / 10) * 10
    return ceilNum
  }

  // 获取当天时间
  function _getDayNow(): { start: string; end: string } {
    const start = dayjs(new Date(new Date().toLocaleDateString()).getTime()).format('YYYY-MM-DD HH:mm:ss')
    const end = dayjs(new Date(new Date().toLocaleDateString()).getTime() + 3600 * 1000 * 24 - 1000).format(
      'YYYY-MM-DD HH:mm:ss'
    )
    deviceSearchData.value.deviceTime = [start, end]
    return { start, end }
  }

  // 左侧树形图
  let nodeKeyMax = 0
  const leftTreeData: Ref<any[]> = ref([])
  async function getLeft() {
    const data = [
      {
        groupName: 'da1',
        deviceGroupId: '1',
        nodeKey: 0
      },
      {
        groupName: 'da2',
        deviceGroupId: '2',
        nodeKey: 0
      }
    ]
    data.forEach((i, idx) => {
      i.nodeKey = idx + 1
    })
    nodeKeyMax = data[data.length - 1].nodeKey
    leftTreeData.value = data
  }
  const props: any = {
    label: 'groupName',
    isLeaf: 'leaf',
    class: customNodeClass
  }

  function customNodeClass(data: any, node: Node) {
    if (node.data.groupName === 'da1') {
      return 'none-box'
    }
    return null
  }
  function treeChange(node, data) {
    console.log('treeChange', node, data)
  }

  interface Tree {
    subTypeName?: string
    deviceId?: string
    deviceSn?: string
    leaf?: boolean
    class?: any
    nodeKey?: number
  }
  function loadNode(node: Node, resolve: (data: Tree[]) => void) {
    if (node.level === 1) {
      nodeKeyMax = nodeKeyMax + 1
      interface TmpData {
        subTypeName?: string
        deviceId?: string
        deviceSn?: string
        leaf?: boolean
        class?: any
        nodeKey?: number
      }
      let data: TmpData[] = [
        {
          subTypeName: '打动送a1打3123',
          deviceId: '1',
          deviceSn: '1'
        },
        {
          subTypeName: 'a33',
          deviceId: '2',
          deviceSn: '3'
        },
        {
          subTypeName: '打动送a3',
          deviceId: '3',
          deviceSn: '3'
        }
      ]
      data.forEach((i, idx) => {
        i.leaf = true
        i.nodeKey = idx + nodeKeyMax
      })
      nodeKeyMax = data[data.length - 1].nodeKey as number
      setTimeout(() => {
        resolve(data)
      }, 500)
    }
    if (node.level === 2) return resolve([])
  }
</script>

<style scoped lang="scss">
  .main-content {
    padding: 10px;
    .main-row {
      //height: calc(100vh - 120px);
      .main-left {
        padding: 10px 0 0;
        border: 1px solid #eeeeee;
      }
      .main-right {
        padding: 16px;
        border: 1px solid #eeeeee;
        .chart-content {
          padding: 14px;
          border: 1px solid #eeeeee;
          position: relative;
          #lineChart {
            width: 100%;
            height: 500px;
          }
          .slider {
            position: absolute;
            left: 10px;
            top: 3%;
          }
        }
      }
    }
  }
  //左侧tree
  :deep(.tree-line) {
    overflow: auto;
    width: 100%;
    height: calc(100vh - 180px);
    .is-expanded {
      display: inline-block;
    }
    .el-tree-node {
      position: relative;
      padding-left: 16px; // 缩进量
    }
    .el-tree-node__children {
      padding-left: 16px; // 缩进量
    }
    // 竖线
    .el-tree-node::before {
      position: absolute;
      top: -26px;
      left: -3px;
      width: 1px;
      height: 100%;
      content: '';
      border-width: 1px;
      border-left: 1px dashed #52627c;
    }
    // 当前层最后一个节点的竖线高度固定
    .el-tree-node:last-child::before {
      height: 38px; // 可以自己调节到合适数值
    }
    // 横线
    .el-tree-node::after {
      position: absolute;
      top: 12px;
      left: -3px;
      width: 24px;
      height: 20px;
      content: '';
      border-width: 1px;
      border-top: 1px dashed #52627c;
    }
    // 去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了
    & > .el-tree-node::after {
      border-top: none;
    }
    & > .el-tree-node::before {
      border-left: none;
    }
    // 展开关闭的icon
    .el-tree-node__expand-icon {
      font-size: 16px;
      // 叶子节点（无子节点）
      &.is-leaf {
        width: 1px;
        color: transparent;
        // display: none;
      }
    }
    .el-tree-node:focus > .el-tree-node__content {
      background-color: rgba(0, 0, 0, 0);
    }
    .is-current > .el-tree-node__content {
      background-color: red !important;
    }
    .el-tree-node__content:hover {
      background-color: red;
    }
    .none-box > .el-tree-node__content > .el-checkbox {
      display: none;
    }
    .none-click {
      cursor: not-allowed;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 2;
    }
  }
</style>
